package com.shengyijie.activity.tab.user;
  

import org.apache.http.HttpResponse;

import com.shengyijie.activity.R;    
import com.shengyijie.activity.UserTabActivity; 
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.database.dataoperate.AccountInfoDB;
import com.shengyijie.model.http.HttpConnectApi;
import com.shengyijie.model.json.JsonParser;  
import com.shengyijie.util.Utility;

import android.app.Activity;  
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class UserActivity extends Activity implements OnClickListener{ 
	 
	private Button login;
	private Button register;
	private EditText et_name;
	private EditText et_password;
	private CheckBox remember;
	public Task task;
	
	private String name;
	private String password;
	private int isRemember=0;
	private  boolean isFirstStart=true;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.login); 
         initView();
         
    } 
    
    public void initView(){
    	login=(Button) this.findViewById(R.id.login);
    	login.setOnClickListener(this); 
    	register=(Button) this.findViewById(R.id.register);
    	register.setOnClickListener(this); 
    	et_name=(EditText) this.findViewById(R.id.name); 
    	et_password=(EditText) this.findViewById(R.id.passwd); 
    	remember=(CheckBox) this.findViewById(R.id.remember); 
    	
    	mypDialog=new ProgressDialog(this); 
        mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
        mypDialog.setIndeterminate(false); 
        mypDialog.setCancelable(false); 
        mypDialog.setOnKeyListener(new DialogOnKeyListener());
    }
    
    public class DialogOnKeyListener implements OnKeyListener {
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				try{
				  mypDialog.hide();
				  if(task.getStatus()==AsyncTask.Status.RUNNING){
		    		 task.cancel(true); 
				  }
			    }catch(Exception e){}
			 }
			return true;
		}
    }
    
    
    protected void onResume() {
	      super.onResume();
	      try{ 
	    	  if(ContextApplication.isUserLogin){
	         	 changeToUserActivity();
	          }
	      }catch(Exception e){}
	 }
    
	@Override
	public void onClick(View v) { 
		switch(v.getId()){
		  case R.id.login:
			   name=et_name.getText().toString().trim();
			   password=et_password.getText().toString().trim();
			   if(name.equals("")){
				    Toast.makeText(this, "邮箱名不能为空", Toast.LENGTH_SHORT).show();
				    et_name.requestFocus();
			   }else if(password.equals("")){
				    Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
				    et_password.requestFocus();
			   }else{
				    if(remember.isChecked())
					   isRemember=1;
				    task=new Task();
				    task.execute(TASK_LOGIN);
			   } 
			   break;
		  case R.id.register:
				Intent i2=new Intent();
				i2.setClass(this, RegisterActivity.class);
				this.startActivity(i2);
				break;
		}
		
	}
	
	public void changeToUserActivity(){
		if(ContextApplication.user.getUserType()==0){
			ContextApplication.tabtype=1;
			Intent i=new Intent();
			i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			i.setClass(this, UserTabActivity.class);
			this.startActivity(i);
		}else{
			Intent i=new Intent();
			i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			i.setClass(this, EnterpriseActivity.class);
			this.startActivity(i);
		}
	}
	
	 public String doLogin(){
	    	String result="login_fail";
	    	HttpConnectApi httpConnect=HttpConnectApi.getInstance();
	        try { 
	            HttpResponse response=httpConnect.doLogin(name, password);
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    ContextApplication.user=jsonParser.getRegister(response);
	           	    if(ContextApplication.user.getState()==ContextApplication.RESULT_CODE_OK){
	           	    	  //if(ContextApplication.user.getUserType()==0)  
	           	    	     Utility.saveUserSession(this, isRemember);
	           	    	  result="login_ok";
	           	    }else if(ContextApplication.user.getState()==ContextApplication.RESULT_CODE_1001){
	           	    	result="login_name_fail";
	           	    }else if(ContextApplication.user.getState()==ContextApplication.RESULT_CODE_1002){
	           	    	result="login_password_fail";
	           	    }else if(ContextApplication.user.getState()==ContextApplication.RESULT_CODE_1003){
	           	    	result="login_ban";
	           	    }
				}
	            return result;
	        }catch (Exception e) {} 
			return result;
	 }
	
	
	
	 private ProgressDialog mypDialog; 
	 private final static int ALERT_LOADING=1; 
	 private final static int RESULT_LOGIN_OK=2;
	 private final static int RESULT_LOGIN_PASSWD_FAIL=3;
	 private final static int RESULT_LOGIN_NAME_FAIL=4;
	 private final static int RESULT_LOGIN_FAIL=5;
	 private final static int RESULT_LOGIN_BAN=6;
	    
	 private final static String TASK_LOGIN="login";   
	 private final Handler handler = new Handler(Looper.getMainLooper()) {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			 	switch (msg.what) { 
				   case ALERT_LOADING:
					    mypDialog.setMessage("正在登录中...");
					    mypDialog.show();
					    break;
				   case RESULT_LOGIN_PASSWD_FAIL:
					   try{
					      mypDialog.hide();
					      et_password.setText("");
					      et_password.requestFocus(); 
					      Toast.makeText(UserActivity.this, "对不起，密码错误", Toast.LENGTH_SHORT).show();
					    }catch(Exception e){}
					     break;
				   case RESULT_LOGIN_NAME_FAIL:
					    try{
						     mypDialog.hide();
						     Toast.makeText(UserActivity.this, "对不起，用户名错误", Toast.LENGTH_SHORT).show();
						     et_name.setText("");
						     et_name.requestFocus(); 
			 	         }catch(Exception e){}
					     break; 
				   case RESULT_LOGIN_FAIL:
					    try{
						     mypDialog.hide();
						     Toast.makeText(UserActivity.this, "对不起，登录失败", Toast.LENGTH_SHORT).show();
						      
			 	         }catch(Exception e){}
					     break; 
				   case RESULT_LOGIN_BAN:
					    try{
						     mypDialog.hide();
						     Toast.makeText(UserActivity.this, "对不起，您已经被禁止登录", Toast.LENGTH_SHORT).show();
			 	         }catch(Exception e){}
					     break; 
                   case RESULT_LOGIN_OK:
                   	     try{
	                    	 mypDialog.hide();  
	                    	 changeToUserActivity();
                   	     }catch(Exception e){}
					     break; 
				}
			}
		};
		
		
	private class Task extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			if(params[0].equals(TASK_LOGIN)){
				return doLogin();
			}else
			    return ""; 
		} 
		@Override
		protected void onPostExecute(String result) {				
			super.onPostExecute(result);

			if(result.equals("login_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOGIN_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("login_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOGIN_OK;
				handler.sendMessage(msg);
			}else if(result.equals("login_name_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOGIN_NAME_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("login_password_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOGIN_PASSWD_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("login_ban")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOGIN_BAN;
				handler.sendMessage(msg);
			} 
		} 
		@Override
		protected void onPreExecute() { 
			super.onPreExecute(); 
			Message msg = Message.obtain();
			msg.what = ALERT_LOADING;
			handler.sendMessage(msg);
			 
		} 
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
	}
    
	public boolean onKeyDown(int keyCode,KeyEvent event) {   
	    if (keyCode == KeyEvent.KEYCODE_BACK) { 
	    	
				 new AlertDialog.Builder(this).setTitle("提示")
				 .setMessage("确定退出？")
				 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) { 
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				  })
				  .setNegativeButton("取消", new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, int whichButton) {
					     }
				  })
				  .show();
	    	
	         return true;   
	     } else
	         return super.onKeyDown(keyCode,event);   
	 }
}